import axios from 'axios'
import qs from 'qs'
import {Message} from 'element-ui'
import NProgress from 'nprogress'
import {getToken} from '@/utils/auth'

// 使用 create 方法创建 axios 实例
const instance = axios.create({
  baseURL: process.env.BASE_API,
  timeout: 15000 // 请求超时时间
})

// 请求拦截器
instance.interceptors.request.use(
  config => {
    // 请求发送前的操作
    let token = getToken()
    if (token) {
      config.headers['Authorization'] = token
    }
    return config
  },
  error => {
    // 请求错误后的操作
    console.log(error) // 打印错误日志, 用于调试
    return Promise.reject(error)
  }
)

// 响应拦截器
instance.interceptors.response.use(response => {
  let res = response.data
  if (res.code !== 0) {
    Message({
      message: res.message,
      type: 'error',
      duration: 3000
    })

    return Promise.reject(new Error('error'))
  } else {
    return response.data
  }
}, (error) => {
  if (error.response) {
    Message({
      message: error.message,
      type: 'error',
      duration: 3000
    })
  }
  return Promise.reject(error)
})

const request = {
  get(url, params) {
    return instance.get(url, {
      params: params
    })
  },
  post(url, params) {
    return instance.post(url, qs.stringify(params))
  },
  put(url, params) {
    return instance.put(url, params, {
      transformRequest: [(params) => {
        return transParams(params)
      }]
    })
  },
  delete(url, params) {
    let parameters
    if (Object.is(params, undefined)) {
      parameters = ''
    } else {
      parameters = '?'
      for (const key in params) {
        // eslint-disable-next-line no-prototype-builtins
        if (params.hasOwnProperty(key) && params[key] !== null) {
          parameters += `${key}=${params[key]}&`
        }
      }
    }
    return instance.delete(`${url}${parameters}`)
  },
  download(url, params, filename) {
    NProgress.start()
    return instance.post(url, params, {
      transformRequest: [(params) => {
        return transParams(params)
      }],
      responseType: 'blob'
    }).then((r) => {
      const content = r.data
      const blob = new Blob([content])
      if ('download' in document.createElement('a')) {
        const elink = document.createElement('a')
        elink.download = filename
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href)
        document.body.removeChild(elink)
      } else {
        navigator.msSaveBlob(blob, filename)
      }
      NProgress.done()
    }).catch((r) => {
      console.error(r)
      NProgress.done()
      Message({
        message: '下载失败',
        type: 'error',
        duration: 3000
      })
    })
  },
  upload(url, params) {
    return instance.post(url, params, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  }
}

function transParams(params) {
  let result = ''
  Object.keys(params).forEach((key) => {
    if (!Object.is(params[key], undefined) && !Object.is(params[key], null)) {
      result += encodeURIComponent(key) + '=' + encodeURIComponent(params[key]) + '&'
    }
  })
  return result
}

export default request
